package org.springframework.beans.factory.context;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/12/13
 */
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {

    protected DefaultListableBeanFactory fac;

    private final AtomicBoolean refreshed = new AtomicBoolean();

    public GenericApplicationContext(){
        fac = new DefaultListableBeanFactory();
    }

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        fac.registerBeanDefinition(beanName,beanDefinition);
    }

    @Override
    public void removeBeanDefinition(String beanName) {
        fac.removeBeanDefinition(beanName);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) {
        return fac.getBeanDefinition(beanName);
    }

    @Override
    public boolean containsBeanDefinition(String beanName) {
        return fac.containsBeanDefinition(beanName);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return fac.getBeanDefinitionNames();
    }

    @Override
    public int getBeanDefinitionCount() {
        return fac.getBeanDefinitionCount();
    }

    @Override
    public boolean isBeanNameInUse(String beanName) {
        return fac.isBeanNameInUse(beanName);
    }


    @Override
    public final DefaultListableBeanFactory getBeanFactory() {
        return fac;
    }

    @Override
    protected void closeBeanFactory() {
        fac = null;
    }

    @Override
    protected void cancelRefresh() {
        this.fac.setSerializationId(null);
        super.cancelRefresh();
    }
    @Override
    protected void refreshBeanFactory() {
        if (!this.refreshed.compareAndSet(false, true)) {
            throw new IllegalStateException(
                    "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
        }
        this.fac.setSerializationId(getId());
    }

}
